package com.swipemaster.elements;

import android.graphics.Bitmap;
import android.graphics.Canvas;

import com.swipemaster.R;
import com.swipemaster.common.Bitmaps;
import com.swipemaster.common.Const;
import com.swipemaster.common.Coords;

/** Represents a single particle. */
public class Particle
{
	/** Possible width of particle in universal units. */
	private static final double PARTICLES_WIDTH[] =
	{ 0.01, 0.014, 0.018, 0.024, 0.028 };
	/** Width of a particle in px. In computations should use only this. */
	private static final int particlesWidth[] = new int[PARTICLES_WIDTH.length];
	/** Particles bitmaps. */
	public static Bitmap[] scaledBitmaps = new Bitmap[PARTICLES_WIDTH.length];
	/** Life of particle in ms. */
	private final int MIN_LIFE_MS = 256;
	private final int MAX_LIFE_MS = 512;
	/** Maximum speed of particle. */
	private final double maxSpeed = Coords.mulByDiag(0.0004);
	/** Gravity describes how fast particles are falling down. */
	private final double gravity = Coords.mulByDiag(0.000001);

	private boolean active = false;
	private int x, y, sizeIndex;
	private double speedX, speedY;
	private int life;

	static
	{
		final Bitmap original = Bitmaps.createBitmap(R.drawable.particle);
		for (int i = 0; i < PARTICLES_WIDTH.length; i++)
		{
			particlesWidth[i] = (int) Coords.mulByDiag(PARTICLES_WIDTH[i]);
			scaledBitmaps[i] = Bitmap.createScaledBitmap(original, particlesWidth[i], particlesWidth[i], true);
		}
	}

	public void compute(int x, int y, int direction)
	{
		active = true;
		life = Const.getRand(MIN_LIFE_MS, MAX_LIFE_MS);
		this.x = x;
		this.y = y;
		sizeIndex = (int) (Math.random() * particlesWidth.length);

		speedX = Math.random() * maxSpeed;
		speedY = Math.random() * maxSpeed;

		switch (direction)
		{
		case Const.LEFT:
			speedX = -speedX;
			if (Math.random() > 0.5)
			{
				speedY = -speedY;
			}
			break;
		case Const.UP:
			speedY = -speedY;
			if (Math.random() > 0.5)
			{
				speedX = -speedX;
			}
			break;
		case Const.DOWN:
			if (Math.random() > 0.5)
			{
				speedX = -speedX;
			}
			break;
		case Const.RIGHT:
			if (Math.random() > 0.5)
			{
				speedY = -speedY;
			}
			break;
		case Const.CENTRAL:
			if (Math.random() > 0.5)
			{
				speedX = -speedX;
			}
			if (Math.random() > 0.5)
			{
				speedY = -speedY;
			}
			break;
		}
	}

	public void draw(Canvas canvas)
	{
		if (active)
		{
			canvas.drawBitmap(scaledBitmaps[sizeIndex], x, y, null);
		}
	}

	/** Updates position and life.
	 * @param interval Interval of time.
	 * @return True, if is still alive, else false. */
	public void updatePosition(int interval)
	{
		if (!active)
		{
			return;
		}
		life -= interval;
		if (life <= 0)
		{
			active = false;
			return;
		}
		speedY += gravity * interval;
		x += speedX * interval;
		y += speedY * interval;
	}
}
